package com.cd.javacxy.module.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cd.javacxy.common.model.entity.CxyAttachment;
import com.cd.javacxy.common.model.entity.CxyAttachmentDownload;
import com.cd.javacxy.common.model.entity.CxyTopic;
import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.FileTopicType;
import com.cd.javacxy.common.model.query.AttachmentDownloadQuery;
import com.cd.javacxy.common.model.query.AttachmentQuery;
import com.cd.javacxy.common.model.vo.CxyUserVo;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.web.dao.CxyAttachmentDao;
import com.cd.javacxy.module.web.dao.CxyAttachmentDownloadDao;
import com.cd.javacxy.module.web.service.CxyAttachmentService;
import com.cd.javacxy.module.web.service.CxyTopicService;
import com.cd.javacxy.module.web.service.CxyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * CxyAttachment的服务接口的实现类
 *
 * @author yanghy
 */
@Service
public class CxyAttachmentServiceImpl implements CxyAttachmentService {


    @Autowired
    private CxyAttachmentDao attachmentDao;

    @Autowired
    private CxyAttachmentDownloadDao attachmentDownloadDao;

    @Autowired
    private CxyUserService userService;

    @Autowired
    private CxyTopicService topicService;

    @Override
    public int addAttachment(CxyAttachment attachment) throws BussinessException {
        final int MAXMARK = 10000;
        Integer mark = attachment.getDownloadMark();
        mark = mark == null ? 0 : mark;
        attachment.setDownloadMark(mark);
        if (StrUtil.isEmpty(attachment.getFileName()) ||
                StrUtil.isEmpty(attachment.getFileUrl()) ||
                mark > MAXMARK
        ) {
            throw new BussinessException("参数错误");
        }
        return this.attachmentDao.insert(attachment);
    }

    @Override
    public CxyAttachment getAttachmentByTopicIdAndFileType(Integer topicId,
                                                           FileTopicType fileTopicType) {
        AttachmentQuery attachmentQuery = new AttachmentQuery();
        attachmentQuery.setTopicId(topicId);
        attachmentQuery.setFileTopicType(fileTopicType);
        List<CxyAttachment> attachments = this.attachmentDao.selectList(attachmentQuery);
        if (attachments.isEmpty()) {
            return null;
        }
        return attachments.get(0);
    }

    @Override
    public CxyAttachment getAttachmentById(Integer attachmentId) {
        if (attachmentId == null) {
            return null;
        }
        AttachmentQuery attachmentQuery = new AttachmentQuery();
        attachmentQuery.setAttachmentId(attachmentId);
        List<CxyAttachment> attachmentList = this.attachmentDao.selectList(attachmentQuery);
        if (attachmentList.isEmpty()) {
            return null;
        }
        return attachmentList.get(0);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = BussinessException.class)
    public CxyAttachment downloadAttachment(SessionUser sessionUser,
                                            Integer attachmentId) throws BussinessException {
        CxyAttachment attachment = this.getAttachmentById(attachmentId);
        if (attachment == null) {
            throw new BussinessException("附件不存在");
        }
        Integer topicId = attachment.getTopicId();
        CxyTopic topic = null;
        FileTopicType fileTopicType = attachment.getTopicType();
        if (fileTopicType == FileTopicType.TOPIC) {
            topic = this.topicService.getTopic(topicId);
            if (topic == null) {
                throw new BussinessException("附件对应的文章不存在");
            }
            this.checkDownloadPermission(topic.getUserId(), sessionUser.getUserId(), attachment.getDownloadMark(), attachmentId);
        } else if (fileTopicType == FileTopicType.BLOG) {

        }
        CxyAttachmentDownload attachmentDownload = new CxyAttachmentDownload();
        attachmentDownload.setAttachmentId(attachmentId);
        attachmentDownload.setUserId(sessionUser.getUserId());
        attachmentDownload.setUserName(sessionUser.getUserName());
        attachmentDownload.setUserIcon(sessionUser.getUserIcon());
        this.attachmentDownloadDao.insert(attachmentDownload);
        attachmentDao.updateDownloadCount(attachmentId);
        return attachment;
    }

    @Override
    public int checkDownloadPermission(Integer topicUserId, Integer userId,
                                       Integer downloadMark, Integer attachmentId)
            throws BussinessException {
        if (!topicUserId.equals(userId) && downloadMark > 0) {
            AttachmentDownloadQuery attachmentDownloadQuery = new AttachmentDownloadQuery();
            attachmentDownloadQuery.setUserId(userId);
            attachmentDownloadQuery.setAttachmentId(attachmentId);
            int downCount = this.attachmentDownloadDao.selectCount(attachmentDownloadQuery);
            if (downCount == 0) {
                int count = this.userService.changeMark(userId, -downloadMark);
                if (count == 0) {
                    throw new BussinessException("积分不足");
                }
            }
        }
        return 0;
    }

    @Override
    public int checkDownload(Integer attachmentId, Integer topicId,
                             SessionUser sessionUser) throws BussinessException {
        if (attachmentId == null || topicId == null) {
            throw new BussinessException("参数错误");
        }
        CxyAttachment attachment = this.getAttachmentById(attachmentId);
        if (attachment == null) {
            throw new BussinessException("附件不存在");
        }
        Integer topicUserId = null;
        FileTopicType fileTopicType = attachment.getTopicType();
        if (fileTopicType == FileTopicType.TOPIC) {
            CxyTopic topic = this.topicService.getTopic(topicId);
            if (topic == null) {
                throw new BussinessException("附件对应的文章不存在");
            }
            topicUserId = topic.getUserId();
        } else if (fileTopicType == FileTopicType.BLOG) {

        }
        AttachmentDownloadQuery attachmentDownloadQuery = new AttachmentDownloadQuery();
        attachmentDownloadQuery.setUserId(sessionUser.getUserId());
        attachmentDownloadQuery.setAttachmentId(attachmentId);
        int downCount = this.attachmentDownloadDao.selectCount(attachmentDownloadQuery);
        if (topicUserId != sessionUser.getUserId() && attachment.getDownloadMark() > 0 && downCount == 0) {
            CxyUserVo user = this.userService.findUserByUserId(sessionUser.getUserId());
            if (user.getMark() < attachment.getDownloadMark()) {
                throw new BussinessException("你的积分只有&nbsp;&nbsp;" + user.getMark() + "&nbsp;&nbsp;分, 积分不足");
            }
        }
        return 0;
    }

    @Override
    public int deleteFile(Integer attachmentId) {
        return this.attachmentDao.delete(attachmentId);
    }


}